import { loginUser } from "../../utils/request";

Page({
  data: {
    isLoading: false,
  },

  onLoad() {
    console.log("进入登录页面...");
  },

  async handleLogin() {
    if (this.data.isLoading) return; // 防止重复触发
    this.setData({ isLoading: true });

    try {
      // Step 1: 调用 wx.getUserProfile 获取用户信息（必须在点击事件中直接调用）
      /* const userProfile = await wx.getUserProfile({
        desc: "For registration or login", // 必填，描述用途
      });

      if (!userProfile || !userProfile.userInfo) {
        throw new Error("获取用户信息失败，用户可能拒绝授权");
      } */
      // Step 1: 调用 wx.getUserProfile 获取用户信息（必须在点击事件中直接调用）
      const userProfile = await this.getUserProfile();
      const { userInfo } = userProfile;
      console.log("用户信息:", userInfo);

      // Step 2: 调用 wx.login 获取 code
      const loginResponse = await wx.login();
      if (!loginResponse.code) {
        console.log("获取微信登录 code 失败");
        throw new Error("登录失败");
      }
      console.log("微信登录 code:", loginResponse.code);

      // Step 3: 构建登录数据
      const loginPayload = {
        code: loginResponse.code,   // 登录凭证
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
      };

      // Step 4: 调用后端接口进行用户的注册或登录
      await this.login(loginPayload);

      // 登录完成后跳转到首页
      wx.switchTab({ url: "/pages/artwork/list/list" });
    } catch (err) {
      console.error("授权或登录失败:", err);
      wx.showToast({
        title: err.message || "登录失败",
        icon: "none",
        duration: 2000,
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },
  async getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: "For registration or login", // 必填，描述用途
        success: (res) => {
          if (res.userInfo) {
            resolve(res);
          } else {
            reject(new Error("授权失败")); // 如果 res.userInfo 为空，认为失败
          }
        },
        fail: (err) => {
          console.error("用户取消授权:", err);
          // 自定义错误消息
          reject(new Error("取消了授权，请点击重新授权"));
        },
      });
    });
  },
  async login(loginPayload) {
    try {
      const response = await loginUser(loginPayload);
      if (response.code === "00000") {
        console.log("登录成功:", response.data);
        wx.setStorageSync("userInfo", response.data.userInfo);
        getApp().globalData.userInfo = response.data.userInfo;
        wx.setStorageSync("token", response.data.token);
        getApp().globalData.token = response.data.token;
      } else {
        throw new Error(response.message || "登录失败");
      }
    } catch (err) {
      console.error("登录失败:", err);
      throw err;
    }
  },
});
